package cn.yuanqiao.archive.wenjianzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.WenjianzhengliMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.ILixianjieshouService;
import cn.yuanqiao.archive.wenjianzhengli.service.IWenjianzhengliService;
import cn.yuanqiao.auth.util.TokenParamUtil;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WenjianzhengliServiceImpl implements IWenjianzhengliService {

    @Autowired
    private WenjianzhengliMapper wenjianzhengliMapper;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private TenantApplyMapper tenantApplyMapper;
    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;
    @Autowired
    private TenantItemFolderMapper tenantItemFolderMapper;
    @Autowired
    private TenantYqdaFolderMapper tenantYqdaFolderMapper;
    @Autowired
    private ITenantCategoryService tenantCategoryService;
    @Autowired
    private TenantCodeRuleMapper tenantCodeRuleMapper;
    @Autowired
    private TenantCodeListMapper tenantCodeListMapper;
    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Autowired
    private ITenantSysDictTypeService tenantSysDictTypeService;
    @Autowired
    private ILixianjieshouService lixianjieshouService;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    /**
     * 日志处理器
     */
    public final static Log logger= LogFactory.getLog(WenjianzhengliServiceImpl.class);
    @Override
    public List<Map<String, Object>> queryListOfWjzl(JSONObject json) {
        String nodeType = json.getString("nodeType");
        List<Map<String, Object>> maps = new ArrayList<>();
        if("f".equalsIgnoreCase(nodeType) || "t".equalsIgnoreCase(nodeType) || "n".equalsIgnoreCase(nodeType)){  //点击全宗节点
            return maps;
        }
        String categoryId = json.getString("categoryId");
        String menuId = json.getString("menuId");
        String sub_table_name = json.getString("sub_table_name");
        String parentNodeType = json.getString("parentNodeType");
        String parentSubTableName = json.getString("parentSubTableName");
        TenantCategory tenantCategoryTable = new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        Integer type = tenantCategory.getType();
        Long groupId = tenantCategory.getGroupId();
        String selectColumn = getSelectColumn(categoryId,menuId,nodeType,type,sub_table_name,
                parentNodeType,parentSubTableName,groupId);
        return queryListOfWjzl(json,selectColumn,tenantCategory);
    }


    @Override
    public List<Map<String, Object>> queryListOfWjzl(JSONObject json, String selectColumn, TenantCategory tenantCategory) {
        String nodeType = json.getString("nodeType"); //f:全宗 a:门类 c:分类 l:层次 t:根节点
        List<Map<String, Object>> maps = new ArrayList<>();

        String state = json.getString("state");
        String ids = json.getString("ids");
        String categoryId = json.getString("categoryId");
        String sub_table_name = json.getString("sub_table_name");
        String menuId = json.getString("menuId");
        String parentNodeType = json.getString("parentNodeType");
        String parentSubTableName = json.getString("parentSubTableName");
        if(!StringUtils.isNotEmpty(categoryId)) {
            throw new ServiceException("categoryId不能为空");
        }
        Integer type = tenantCategory.getType();

        JSONArray searchCondition = json.getJSONArray("searchCondition");//前端查询条件
        //拼接查询条件
        StringBuilder queryCondition = new StringBuilder();
        queryCondition.append("state = "+state+" and is_del = 0 and");
        //传id的话拼接id
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            if(idArr.length>1) queryCondition.append(" id in ("+ids+") and");
            else queryCondition.append(" id = ").append(ids).append(" and");
        }

        concatQueryCondition(searchCondition,queryCondition);
        //查询的表名
        String tableName = getSubTableName(json,tenantCategory);
        if("c".equalsIgnoreCase(nodeType)){
            String propertyName = json.getString("propertyName");
            String propertyValue = json.getString("propertyValue");
            queryCondition.append(" ").append(propertyName).append(" = '").append(propertyValue).append("' and");
        }
        String finalQueryCondition = "";
        String queryConditionStr = queryCondition.toString();
        if(queryConditionStr.endsWith("and")){
            finalQueryCondition = queryConditionStr.substring(0,queryConditionStr.length()-3);
        }
        //排序查询
        String orderColumn = getOrderColumn(categoryId, menuId,nodeType,type,sub_table_name,
                parentNodeType,parentSubTableName);
        if("order by".equalsIgnoreCase(orderColumn.trim())) {
            orderColumn = "";
        }
        maps = wenjianzhengliMapper.queryListOfWjzl(tableName, selectColumn, finalQueryCondition,orderColumn);
        return maps;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int cancelAccept(String ids,Long categoryId) {
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory tenantCategory1 = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCategory.getTableName());
        Integer type = tenantCategory1.getType();
        String itemTableName = tenantCategory1.getItemTableName();
        String folderTableName = tenantCategory1.getFolderTableName();
        String fileTableName = tenantCategory1.getFileTableName();

        String vIds = null;
        String fIds = null;
        for(int i=type;i>=0;i--){
            if(i==3){
                TenantYqItem tenantYqItem = new TenantYqItem();
                wenjianzhengliMapper.cancelAccept(ids,"item_id",tenantYqItem.getTableName());
                wenjianzhengliMapper.cancelAccept(ids,"id",itemTableName);
                TenantItemFolder tenantItemFolder = new TenantItemFolder();
                List<String> longs = tenantItemFolderMapper.selectFolderIdByItemId(ids,tenantItemFolder.getTableName());
                if(longs.size()!=0){
                    vIds = String.join(",",longs);
                }
            }
            if(i==1){
                TenantYqFolder tenantYqFolder = new TenantYqFolder();
                TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
                if(vIds!=null){
                    wenjianzhengliMapper.cancelAccept(vIds,"folder_id",tenantYqFolder.getTableName());
                    wenjianzhengliMapper.cancelAccept(vIds,"id",folderTableName);
                    List<String> longs = tenantYqdaFolderMapper.selectFileIdByFolderId(vIds,tenantYqdaFolder.getTableName());
                    if(longs.size()!=0){
                        fIds = String.join(",",longs);
                    }
                }else{
                    wenjianzhengliMapper.cancelAccept(ids,"folder_id",tenantYqFolder.getTableName());
                    wenjianzhengliMapper.cancelAccept(ids,"id",folderTableName);
                    List<String> longs = tenantYqdaFolderMapper.selectFileIdByFolderId(ids,tenantYqdaFolder.getTableName());
                    if(longs.size()!=0){
                        fIds = String.join(",",longs);
                    }
                }
            }
            if(i==0){
                TenantYqda tenantYqda = new TenantYqda();
                if(fIds!=null){
                    wenjianzhengliMapper.cancelAccept(fIds,"da_id",tenantYqda.getTableName());
                    wenjianzhengliMapper.cancelAccept(fIds,"id",fileTableName);
                }else{
                    wenjianzhengliMapper.cancelAccept(ids,"da_id",tenantYqda.getTableName());
                    wenjianzhengliMapper.cancelAccept(ids,"id",fileTableName);
                }
            }
        }
        return 1;
    }

    public int pieceInnerNumber(JSONObject json){
        String tenantCode = SecurityUtils.getTenantCode();
        String categoryId = json.getString("categoryId");
        String folderId = json.getString("folderId");
        String ids = json.getString("ids");
        String isMore = json.getString("isMore");
        //查询规则以及明细是否存在
        checkRuleAndList(categoryId);
        //获取档号规则
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        tenantCodeRule.setCategoryModelId(Long.valueOf(categoryId));
        List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(tenantCodeRule);

        TenantYqda tenantYqda = new TenantYqda();
        TenantCategory tenantCategoryTable = new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        String folderTableName = tenantCategory.getFolderTableName();
        String fileTableName = tenantCategory.getFileTableName();
        //TenantCodeRule finalCodeRule = new Tenan;
        String vdh = null;
        for(int i=0;i<tenantCodeRules.size();i++){
            TenantCodeRule codeRule = tenantCodeRules.get(i);
            String vcolumnName = codeRule.getvColumnname();
            //先检查所属案卷档号是否存在
            try{
                vdh = yqdaarticulatedMapper.getSingle("select " + vcolumnName + " from " + folderTableName + " where id = " + folderId);
                if(!StringUtils.isNotEmpty(vdh)){
                    throw new ServiceException("案卷中档号为空不能排卷内档号");
                }else{
                    tenantCodeRule = codeRule;
                    break;
                }
            }catch (Exception e){
                if("true".equals(isMore)){
                    if(e instanceof ServiceException) return -1;
                }
                e.printStackTrace();
                continue;
            }
        }
        String fcolumnName = tenantCodeRule.getfColumnname();
        TenantCodeList tenantCodeList = new TenantCodeList();
        String tableName = tenantCodeList.getTableName();
        List<String> fzlx = tenantCodeListMapper.selectNodeValByIdAndType(tenantCodeRule.getId(), "f", tableName);
        List<String> fgdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(tenantCodeRule.getId(), "f", tableName);
        List<String> fbuling1 = tenantCodeListMapper.selectNodeValByIdAndTypeLen(tenantCodeRule.getId(), "f", tableName);
        String fbuling = fbuling1.get(fbuling1.size()-1);
        String fqueryColumnMax = "max("+fzlx.get(0)+")";
        String[] split = ids.split(",");
        List<String> daIds = Arrays.asList(split);
        String single = yqdaarticulatedMapper.getSingle("select to_char(wm_concat(id)) from " + fileTableName + " " +
                "where is_del=0 and id in (select da_id from " + tenantCode + "_YQDA_FOLDER WHERE FOLDER_ID = " + folderId + ") and id not in ("+daIds.stream().collect(Collectors.joining(","))+")");
        String queryCondition="id in ("+single+")";
        //String queryCondition="id not in ("+daIds.stream().collect(Collectors.joining(","))+")";
        int maxfNumber = 0;
        String maxfno = wenjianzhengliMapper.selectColumnByCondition(fileTableName, fqueryColumnMax, queryCondition);
        if(StringUtils.isNotEmpty(maxfno)) maxfNumber = Integer.valueOf(maxfno);
        Iterator<String> iterator2 = daIds.iterator();
        while (iterator2.hasNext()){
            maxfNumber+=1;
            String finalfNo = String.format("%0"+fbuling+"d", maxfNumber);
            String daids = iterator2.next();
            String updateColumns = fcolumnName+"='"+vdh+fgdz.get(0)+finalfNo+"',"+fzlx.get(0)+"='"+maxfNumber+"'";
            wenjianzhengliMapper.updateColumnById("id",daids,updateColumns,fileTableName);
            wenjianzhengliMapper.updateColumnById("da_id",daids,updateColumns,tenantYqda.getTableName());
        }

        return 1;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int pieceNumber(JSONObject json) {
        int msg=1;
        String categoryId = json.getString("categoryId");
        //获取type
        Integer type = Integer.valueOf(json.getString("type"));
        String ids = json.getString("ids");
        TenantCategory tenantCategoryTable = new TenantCategory();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        Integer type1 = tenantCategory.getType();
        //如果是卷内件
        if(type==0 && type!=type1){
            String[] daIds = ids.split(",");
            boolean f = false;
            for(int i=0;i<daIds.length;i++){
                String da_id = daIds[i];
                List<String> strings = tenantYqdaFolderMapper.selectFolderIdByFileId(da_id, tenantYqdaFolder.getTableName());
                String folderId = strings.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("categoryId",categoryId);
                jsonObject.put("ids",da_id);
                jsonObject.put("folderId",folderId);
                jsonObject.put("isMore","true");
                int i1 = pieceInnerNumber(jsonObject);
                if(i1==-1) f = true;
            }
            if(f) return -1;
            else return 1;
        }
        //查询规则以及明细是否存在
        checkRuleAndList(categoryId);
        Map<String,String> finalIds = new HashMap<>();


        //获取tableName
        String subTableName = json.getString("sub_table_name");
        List<Map<String, Object>> maps = wenjianzhengliMapper.selectRqById(ids, subTableName);
        Iterator<Map<String, Object>> iterator = maps.iterator();
        while (iterator.hasNext()){
            Map<String, Object> next = iterator.next();
            String rq = String.valueOf(next.get("RQ"));
            rq = rq.replaceAll("-","");
            String id = String.valueOf(next.get("ID"));
            finalIds.put(id,rq);
        }
        //排除日期不在规则内的 以及 案卷号或件号等已生成的
        int msg2 = checkRqRight(categoryId, finalIds, type, subTableName, null);
        if(finalIds.size()==0) return msg2;

        //生成档号
        String uuid = UUID.randomUUID().toString();
        int count = 0;
        for(;;){
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(subTableName, uuid);
            if(flag){
                try {
                    msg = generateDH(categoryId, String.valueOf(type), finalIds, subTableName, tenantCategory.getFileTableName());
                    if(uuid.equals(redisTemplate.opsForValue().get(subTableName))) redisTemplate.delete(subTableName);
                    break;
                }catch (Exception e){
                    if(uuid.equals(redisTemplate.opsForValue().get(subTableName))) redisTemplate.delete(subTableName);
                    e.printStackTrace();
                    throw new ServiceException(e.getMessage());
                }
            }else{
                if(count==20) throw new ServiceException("服务繁忙，请稍后重试");
                count++;
                try {
                    Thread.sleep(500);  //每隔500毫秒重试
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        if(msg==1 && msg2!=1) msg = msg2;
        return msg;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertPieceNumber(JSONObject json) {
        String categoryId = json.getString("categoryId");
        Long ruleId = json.getLong("ruleId");
        String buling = json.getString("buling");
        String id = json.getString("ids");  //单个id
        //获取type
        Integer type = Integer.valueOf(json.getString("type"));
        TenantCategory tenantCategoryTable = new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        Integer type1 = tenantCategory.getType();
        TenantCodeRule codeRule = new TenantCodeRule();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        TenantCodeList tenantCodeList = new TenantCodeList();
        TenantYqda tenantYqda = new TenantYqda();
        //如果是卷内件手动排档号先查询对应案卷是否有档号
        if(type==0 && type1!=type){
            TenantCodeRule codeRule1 = tenantCodeRuleMapper.selectYqdaCoderuleModelById(ruleId, codeRule.getTableName());
            String dhColumn = codeRule1.getvColumnname();
            List<String> folderId = tenantYqdaFolderMapper.selectFolderIdByFileId(id, tenantYqdaFolder.getTableName());
            String vdh = yqdaarticulatedMapper.getSingle("select " + dhColumn + " from " + tenantCategory.getFolderTableName() + " where id = " + folderId.get(0));
            if(!StringUtils.isNotEmpty(vdh)){
                throw new ServiceException("案卷中档号为空不能排卷内档号");
            }
            List<String> fgdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(ruleId, "f", tenantCodeList.getTableName());
            List<String> zlx = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, "f", tenantCodeList.getTableName());
            String lastZlx = zlx.get(zlx.size()-1);
            String lastZlxVal = json.getString(lastZlx);  //手动输入的件号或卷号等
            lastZlxVal = String.format("%0"+buling+"d", Integer.valueOf(lastZlxVal));
            String dhColumnVal = vdh+fgdz.get(0)+lastZlxVal;
            String num = wenjianzhengliMapper.selectColumnByCondition(tenantCategory.getFileTableName(), "count(1)", dhColumn + "='" + dhColumnVal + "' and is_del=0");
            if(StringUtils.isNotEmpty(num)){
                Integer i = Integer.valueOf(num);
                if(i>0) throw new ServiceException("该档号已存在");
            }
            String updateColumn = dhColumn+"='"+dhColumnVal+"',"+lastZlx+"='"+lastZlxVal+"'";
            wenjianzhengliMapper.updateColumnById("id",id,updateColumn,tenantCategory.getFileTableName());
            wenjianzhengliMapper.updateColumnById("da_id",id,updateColumn,tenantYqda.getTableName());
            return 1;
        }
        String vfeType = 1==type?"v":0==type?"f":"";

        TenantYqFolder tenantYqFolder = new TenantYqFolder();

        //获取tableName
        String subTableName = json.getString("sub_table_name");
        List<String> zlx = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, vfeType, tenantCodeList.getTableName());
        List<String> gdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(ruleId, vfeType, tenantCodeList.getTableName());
        TenantCodeRule codeRule1 = tenantCodeRuleMapper.selectYqdaCoderuleModelById(ruleId, codeRule.getTableName());
        String dhColumn = type==1?codeRule1.getvColumnname():type==0?codeRule1.getfColumnname():"dh";
        String fdhColumn = codeRule1.getfColumnname();
        String lastZlx = zlx.get(zlx.size()-1);
        String lastZlxVal = json.getString(lastZlx);  //手动输入的件号或卷号等
        String queryColumn = "";
        for(int k=0;k<zlx.size()-1;k++){
            queryColumn += zlx.get(k)+",";
        }
        if(queryColumn.endsWith(",")) queryColumn = queryColumn.substring(0,queryColumn.length()-1);


        //判断档号组成字段是否有空的
        List<Map<String, Object>> list = wenjianzhengliMapper.selectColumnById(Long.valueOf(id), subTableName, queryColumn);
        Map<String, Object> map = list.get(0);
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Object> next = iterator.next();
            String value = String.valueOf(next.getValue());
            if(StringUtils.isEmpty(value) || "null".equals(value)){
                return -1;
            }
        }


        String dhColumnVal = "";
        for(int l=0;l<zlx.size()-1;l++){
            String k = zlx.get(l);
            dhColumnVal += map.get(k)+gdz.get(l);
        }
        lastZlxVal = String.format("%0"+buling+"d", Integer.valueOf(lastZlxVal));
        dhColumnVal+=lastZlxVal;
        String num = wenjianzhengliMapper.selectColumnByCondition(subTableName, "count(1)", dhColumn + "='" + dhColumnVal + "' and is_del=0");
        if(StringUtils.isNotEmpty(num)){
            Integer i = Integer.valueOf(num);
            if(i>0) throw new ServiceException("该档号已存在");
        }
        String updateColumn = dhColumn+"='"+dhColumnVal+"',"+lastZlx+"='"+lastZlxVal+"'";
        wenjianzhengliMapper.updateColumnById("id",id,updateColumn,subTableName);
        if(type==0){
            wenjianzhengliMapper.updateColumnById("da_id",id,updateColumn,tenantYqda.getTableName());
        }else if(type==1){
            wenjianzhengliMapper.updateColumnById("folder_id",id,updateColumn,tenantYqFolder.getTableName());
            List<String> daIds = tenantYqdaFolderMapper.selectFileIdByFolderId(id, tenantYqdaFolder.getTableName());
            if(daIds.size()>0){
                List<String> fzlx = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, "f", tenantCodeList.getTableName());
                List<String> fgdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(ruleId, "f", tenantCodeList.getTableName());
                List<String> fbuling1 = tenantCodeListMapper.selectNodeValByIdAndTypeLen(ruleId, "f", tenantCodeList.getTableName());
                String fbuling = fbuling1.get(fbuling1.size()-1);
                queryColumn = "max("+fzlx.get(0)+")";
                String queryCondition="id in ("+daIds.stream().collect(Collectors.joining(","))+")";
                int maxfNumber = 0;
                String maxfno = wenjianzhengliMapper.selectColumnByCondition(tenantCategory.getFileTableName(), queryColumn, queryCondition);
                if(StringUtils.isNotEmpty(maxfno)) maxfNumber = Integer.valueOf(maxfno);
                Iterator<String> iterator2 = daIds.iterator();
                while (iterator2.hasNext()){
                    maxfNumber+=1;
                    String finalfNo = String.format("%0"+fbuling+"d", maxfNumber);
                    String daids = iterator2.next();
                    updateColumn = fdhColumn+"='"+dhColumnVal+fgdz.get(0)+finalfNo+"',"+fzlx.get(0)+"='"+maxfNumber+"'";
                    wenjianzhengliMapper.updateColumnById("id",daids,updateColumn,tenantCategory.getFileTableName());
                    wenjianzhengliMapper.updateColumnById("da_id",daids,updateColumn,tenantYqda.getTableName());
                }
            }
        }
        return 1;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int clearNumber(JSONObject json) {
        String categoryId = json.getString("categoryId");
        //查询规则以及明细是否存在
        checkRuleAndList(categoryId);
        String ids = json.getString("ids");
        TenantCategory tenantCategoryTable = new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        String fileTableName = tenantCategory.getFileTableName();
        //获取tableName
        //String subTableName = getSubTableName(json, tenantCategory);
        String subTableName = json.getString("sub_table_name");
        //获取type
        Integer type = Integer.valueOf(json.getString("type"));
        String vfeType = 1==type?"v":0==type?"f":"v";
        //获取档号存储字段以及规则
        String[] idArr = ids.split(",");
        int count = 0;
        TenantCodeRule codeRule = new TenantCodeRule();
        TenantCodeList tenantCodeList = new TenantCodeList();
        TenantYqda tenantYqda = new TenantYqda();
        TenantYqFolder tenantYqFolder = new TenantYqFolder();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        boolean isExist = false;
        TenantCodeRule codeRule2 = new TenantCodeRule();
        codeRule2.setIsMoren(1);
        codeRule2.setCategoryModelId(Long.valueOf(categoryId));
        List<TenantCodeRule> tenantCodeRules = null;
        for(int i=0;i<idArr.length;i++){
            String updateColumn = "";
            String id = idArr[i];
            List<Map<String, Object>> list = wenjianzhengliMapper.selectColumnById(Long.valueOf(id), subTableName, "rq");
            Map<String, Object> map = list.get(0);
            String value = String.valueOf(map.get("RQ"));
            value = value.replaceAll("-","");
            Long ruleId = null;
            if(StringUtils.isNotEmpty(value) && !"null".equals(value)){
                value = addZero(value);  //不足八位的rq 末尾补零
                Integer rq = Integer.valueOf(value);
                ruleId = tenantCodeRuleMapper.selectIdByRqAndCateId(Long.valueOf(categoryId), rq, codeRule.getTableName());
            }
            if(ruleId==null){
                if(tenantCodeRules==null){
                    tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(codeRule2);
                }
                if(tenantCodeRules.size()>0){
                    TenantCodeRule codeRule3 = tenantCodeRules.get(0);
                    ruleId = codeRule3.getId();
                }else{
                    isExist = true;
                    continue;
                }
            }
            List<String> zlx = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, vfeType, tenantCodeList.getTableName());
            String lastZlx = zlx.get(zlx.size()-1);
            TenantCodeRule codeRule1 = tenantCodeRuleMapper.selectYqdaCoderuleModelById(ruleId, codeRule.getTableName());
            String fDhColumn = codeRule1.getfColumnname();  //件档号赋值字段
            String vDhColumn = codeRule1.getvColumnname();  //卷档号赋值字段
            updateColumn = (0==type?fDhColumn:1==type?vDhColumn:"dh")+"=null,"+lastZlx+"=null";
            String single = yqdaarticulatedMapper.getSingle("select " + (0 == type ? fDhColumn : 1 == type ? vDhColumn : "dh") + " from " + subTableName + " where id = " + id);
            if(!StringUtils.isNotEmpty(single)) count++;
            wenjianzhengliMapper.updateColumnById("id", id, updateColumn, subTableName);
            if(0==type){  //件
                wenjianzhengliMapper.updateColumnById("da_id",id,updateColumn,tenantYqda.getTableName());
            }else if(1==type){  //卷
                wenjianzhengliMapper.updateColumnById("folder_id",id,updateColumn,tenantYqFolder.getTableName());
                List<String> daIds = tenantYqdaFolderMapper.selectFileIdByFolderId(id, tenantYqdaFolder.getTableName());
                if(daIds.size()>0){
                    for(int j=0;j<daIds.size();j++){
                        String da_id = daIds.get(j);
                        List<String> f = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, "f", tenantCodeList.getTableName());
                        String fColumn = f.get(0);
                        updateColumn = fDhColumn+"=null,"+fColumn+"=null";
                        wenjianzhengliMapper.updateColumnById("id",da_id,updateColumn,fileTableName);
                        wenjianzhengliMapper.updateColumnById("da_id",da_id,updateColumn,tenantYqda.getTableName());
                    }
                }
            }
        }
        if(isExist){
            throw new ServiceException("根据日期未找到对应档号规则");
        }
        if(count==idArr.length) return -1;
        return 1;
    }

    @Override
    public Map<String,Object> getLastZlx(JSONObject json) {
        String id = json.getString("ids");
        String categoryId = json.getString("categoryId");
        TenantCodeRule codeRule = new TenantCodeRule();
        TenantCodeList tenantCodeList = new TenantCodeList();
        //TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        //获取tableName
        //String subTableName = getSubTableName(json, tenantCategory);
        String subTableName = json.getString("sub_table_name");
        //获取type
        //Integer type = getFinalType(json);
        Integer type = Integer.valueOf(json.getString("type"));
        String vfeType = 0==type?"f":1==type?"v":"";
        //查询规则以及明细是否存在
        checkRuleAndList(categoryId);
        List<Map<String, Object>> list = wenjianzhengliMapper.selectColumnById(Long.valueOf(id), subTableName, "rq");
        Map<String, Object> map = list.get(0);
        String rq = String.valueOf(map.get("RQ"));
        rq = rq.replaceAll("-","");
        Long ruleId = null;
        if(StringUtils.isNotEmpty(rq) && !"null".equals(rq)){
            String s = addZero(rq);
            Integer rqInt = Integer.valueOf(s);
            ruleId = tenantCodeRuleMapper.selectIdByRqAndCateId(Long.valueOf(categoryId), rqInt, codeRule.getTableName());
            if(ruleId==null){
                TenantCodeRule codeRule1 = new TenantCodeRule();
                codeRule1.setIsMoren(1);
                codeRule1.setCategoryModelId(Long.valueOf(categoryId));
                List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(codeRule1);
                if(tenantCodeRules.size()>0){
                    TenantCodeRule codeRule2 = tenantCodeRules.get(0);
                    ruleId = codeRule2.getId();
                }else{
                    throw new ServiceException("未找到对应档号定义规则");
                }
            }
        }else{   //日期为空 查找默认规则
            TenantCodeRule codeRule1 = new TenantCodeRule();
            codeRule1.setIsMoren(1);
            codeRule1.setCategoryModelId(Long.valueOf(categoryId));
            List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(codeRule1);
            if(tenantCodeRules.size()>0){
                TenantCodeRule codeRule2 = tenantCodeRules.get(0);
                ruleId = codeRule2.getId();
            }else{
                throw new ServiceException("未找到对应档号定义规则");
            }
        }
        if(ruleId==null) throw new ServiceException("未找到对应档号定义规则");
        List<String> zlx = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, vfeType, tenantCodeList.getTableName());
        List<String> buling = tenantCodeListMapper.selectNodeValByIdAndTypeLen(ruleId, vfeType, tenantCodeList.getTableName());
        String lastZlx = zlx.get(zlx.size()-1);
        TenantFields tenantFields = new TenantFields();
        tenantFields.setFieldName(lastZlx);
        tenantFields.setType(String.valueOf(type));
        List<TenantFields> tenantFields1 = tenantFieldsMapper.selectTenantFieldsList(tenantFields);
        TenantFields tenantFields2 = tenantFields1.get(0);
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("fieldCaption",tenantFields2.getFieldCaption());
        hashMap.put("fieldName",tenantFields2.getFieldName());
        hashMap.put("ruleId",ruleId);
        hashMap.put("buling",buling.get(buling.size()-1));
        return hashMap;
    }

    //字符串不足8位末尾补零
    public String addZero(String str){
        int length = str.length();
        if(length<8){
            int b = 8-length;
            for(int i=0;i<b;i++){
                str+="0";
            }
            return str;
        }
        return str;
    }
    public String checkDH(String dh,String categoryId,Integer type){
        String vfeType = type==1?"v":type==0?"f":"";
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        tenantCodeRule.setCategoryModelId(Long.valueOf(categoryId));
        List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(tenantCodeRule);
        TenantCodeList tenantCodeList = new TenantCodeList();
        boolean isRight = true;
        String jh = "";
        for(int i = 0;i<tenantCodeRules.size();i++){
            TenantCodeRule codeRule = tenantCodeRules.get(i);
            Long id = codeRule.getId();
            String tableName = tenantCodeList.getTableName();
            //List<String> zlx = tenantCodeListMapper.selectNodeValByIdAndType(id, vfeType, tableName);
            List<String> gdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(id, vfeType, tableName);
            List<String> buling1 = tenantCodeListMapper.selectNodeValByIdAndTypeLen(id, vfeType, tableName);
            String buling = buling1.get(buling1.size()-1);
            String gdzStr = "";
            for(int j=0;j<gdz.size();j++){
                gdzStr+=gdz.get(j);
            }
            boolean b1 = true;
            boolean b2 = true;
            if(!"".equals(gdzStr)){
                //检查分隔符是否匹配
                int index = 0;
                // Iterate through all of the characters in the substring.
                char[] chars = gdzStr.toCharArray();
                for(int k=0;k<chars.length;k++){
                    index = dh.indexOf(chars[k], index);
                    // If the method returned -1, the character was not found, so the result is false.
                    if (index == -1){
                        b1 =  false;
                        break;
                    }
                }
                if(b1){ //判断段数
                    Map<Character, Integer> map = new HashMap<>();
                    for(int l=0;l<chars.length;l++){
                        char aChar = chars[l];
                        if(map.containsKey(aChar)){
                            Integer integer = map.get(aChar);
                            integer = integer+1;
                            map.put(aChar,integer);
                        }else{
                            map.put(aChar,1);
                        }
                    }
                    int oldLen = dh.length();
                    Set<Map.Entry<Character, Integer>> entries = map.entrySet();
                    Iterator<Map.Entry<Character, Integer>> iterator = entries.iterator();
                    while(iterator.hasNext()){
                        Map.Entry<Character, Integer> next = iterator.next();
                        Character key = next.getKey();
                        Integer value = next.getValue();
                        String newStr = dh.replace(Character.toString(key), "");
                        if(oldLen-newStr.length()!=value){
                            b2 = false;
                            break;
                        }
                    }
                }
                if(b1 && b2){   //检查补零是否正确
                    char lastGdz = chars[chars.length-1];
                    String lastZlx = dh.substring(dh.lastIndexOf(lastGdz)+1,dh.length());
                    if(lastZlx.length()>Integer.valueOf(buling)){
                        isRight = false;
                    }else{
                        jh = lastZlx;
                    }
                }else{
                    isRight = false;
                }
            }
            if(isRight) break;
        }
        if(!"".equals(jh)){
            jh = String.valueOf(Integer.parseInt(jh));
        }
        return jh;
    }

    @Override
    public int generateDH(String categoryId, String type, Map<String,String> finalIds, String subTableName, String fileTableName){
        int msg = 1;
        String vfeType = "1".equals(type)?"v":"0".equals(type)?"f":"";
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        tenantCodeRule.setCategoryModelId(Long.valueOf(categoryId));
        List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(tenantCodeRule);
        TenantYqFolder tenantYqFolder = new TenantYqFolder();
        TenantYqda tenantYqda = new TenantYqda();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        for(int i=0;i<tenantCodeRules.size();i++){
            Map<String, Object> mapOfJH = new HashMap<>();
            TenantCodeRule codeRule = tenantCodeRules.get(i);
            Integer starttime = codeRule.getStarttime();
            Integer endtime = codeRule.getEndtime();
            Long id = codeRule.getId();
            Integer isMoren = codeRule.getIsMoren();
            TenantCodeList tenantCodeList = new TenantCodeList();
            String tableName = tenantCodeList.getTableName();
            List<String> zlx = tenantCodeListMapper.selectNodeValByIdAndType(id, vfeType, tableName);
            if(zlx==null || zlx.size()==0) continue;
            List<String> gdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(id, vfeType, tableName);
            if(gdz==null || gdz.size()==0) continue;
            List<String> buling1 = tenantCodeListMapper.selectNodeValByIdAndTypeLen(id, vfeType, tableName);
            if(buling1==null || buling1.size()==0) continue;
            String buling = buling1.get(buling1.size()-1);
            String fDhColumn = codeRule.getfColumnname();  //件档号赋值字段
            String vDhColumn = codeRule.getvColumnname();  //卷档号赋值字段
            String orderStr = codeRule.getOrderStr();   //排序规则
            //找到日期符合该规则的id
            List<String> idsArr = new ArrayList<>();
            Set<Map.Entry<String, String>> entries = finalIds.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            while (iterator.hasNext()){
                Map.Entry<String, String> next = iterator.next();
                String idStr = next.getKey();
                String value = next.getValue();
                String[] split = value.split(":");
                if(split.length==1){
                    value = split[0];
                }else{   //有件号的处理
                    value = split[0];
                    mapOfJH.put(idStr,split[1]);
                }
                if((StringUtils.isNotEmpty(value) && isMoren==1) || (!StringUtils.isNotEmpty(value) && isMoren==1)){
                    idsArr.add(idStr);
                    continue;
                }
                value = addZero(value);
                Integer rq = Integer.valueOf(value);
                if(rq>=starttime && rq<=endtime) idsArr.add(idStr);
            }

            String queryColumn = "";
            for(int k=0;k<zlx.size()-1;k++){
                queryColumn += zlx.get(k)+",";
            }
            if(queryColumn.endsWith(",")) queryColumn = queryColumn.substring(0,queryColumn.length()-1);

            //判断档号组成字段是否为空
            for(int k=0;k<idsArr.size();k++){
                String idt = idsArr.get(k);
                List<Map<String, Object>> list = wenjianzhengliMapper.selectColumnById(Long.valueOf(idt), subTableName, queryColumn);
                Map<String, Object> map = list.get(0);
                Set<Map.Entry<String, Object>> entries1 = map.entrySet();
                Iterator<Map.Entry<String, Object>> iterator1 = entries1.iterator();
                boolean isRemove = false;
                while(iterator1.hasNext()){
                    Map.Entry<String, Object> next = iterator1.next();
                    String value = String.valueOf(next.getValue());
                    if(StringUtils.isEmpty(value) || "null".equals(value)){
                        isRemove = true;
                        msg = -6;
                        continue;
                    }
                }
                if(isRemove) {
                    idsArr.remove(k);
                    k--;
                }
            }
            if(idsArr.size()==0) continue;
            //分批
            Map<String, String> mapf = inBatches(orderStr, subTableName, idsArr, queryColumn, zlx);
            Set<Map.Entry<String, String>> entriesf = mapf.entrySet();
            Iterator<Map.Entry<String, String>> iteratorf = entriesf.iterator();
            while (iteratorf.hasNext()){
                Map.Entry<String, String> next = iteratorf.next();
                String idsMore = next.getValue();
                String[] split = idsMore.split(",");
                Integer maxNumber = 0;
                String queryCondition = "";
                for(int j=0;j<split.length;j++){
                    maxNumber++;
                    String idStr = split[j];

                    //maxNumber++;
                    List<Map<String, Object>> list = wenjianzhengliMapper.selectColumnById(Long.valueOf(idStr), subTableName, queryColumn);
                    Map<String, Object> map = list.get(0);
                    //拼接查询条件
                    String no = "";
                    //String queryCondition = "";
                    if(j==0){
                        queryCondition = "is_del = 0 and ";
                        Set<Map.Entry<String, Object>> entries1 = map.entrySet();
                        Iterator<Map.Entry<String, Object>> iterator1 = entries1.iterator();
                        while (iterator1.hasNext()){
                            Map.Entry<String, Object> next1 = iterator1.next();
                            String key = next1.getKey();
                            if(!"ID".equalsIgnoreCase(key)){
                                Object value = next1.getValue();
                                queryCondition += " " + key + "= '"+value+"' and";
                            }
                        }
                        if(queryCondition.endsWith("and")) queryCondition = queryCondition.substring(0,queryCondition.length()-3);
                        String queryColumnMax = "max("+zlx.get(zlx.size()-1)+")";
                        //查询最大件号或卷号
                        no = wenjianzhengliMapper.selectColumnByCondition(subTableName, queryColumnMax, queryCondition);
                    }
                    if(mapOfJH.containsKey(idStr)){  //此id数据存在件号
                        String jh = String.valueOf(mapOfJH.get(idStr));

                        String single = yqdaarticulatedMapper.getSingle("select count(1) from " + subTableName + " " +
                                "where " + zlx.get(zlx.size()-1) + "='" + jh + "' and "+queryCondition+" and id!="+idStr+"");
                        if(!"0".equals(single)){   //件号已存在 跳过
                            maxNumber--;
                            msg=-2;
                            continue;
                        }else{
                            no = String.valueOf(Integer.valueOf(jh)-1);
                        }
                    }
                    if(StringUtils.isNotEmpty(no)) maxNumber = Integer.valueOf(no)+1;
                    if(maxNumber.toString().length()>Integer.valueOf(buling)){  //案卷号长度超出限制提示
                        //throw new ServiceException("生成档号末位超出补零位数，请修改档号规则");
                        msg = -5;
                        break;
                    }
                    String finalNo =String.format("%0"+buling+"d", maxNumber);
                    //更新字段
                    String updateColumns = ("1".equals(type)?vDhColumn:"0".equals(type)?fDhColumn:"dh")+"='";
                    String vDH = "";
                    for(int l=0;l<zlx.size()-1;l++){
                        String k = zlx.get(l);
                        updateColumns += map.get(k)+gdz.get(l);
                        vDH += map.get(k)+gdz.get(l);
                    }
                    vDH+=finalNo;
                    updateColumns+=finalNo+"',"+zlx.get(zlx.size()-1)+"='"+maxNumber+"'";
                    wenjianzhengliMapper.updateColumnById("id",idStr,updateColumns,subTableName);
                    if("1".equals(type)){  //卷
                        wenjianzhengliMapper.updateColumnById("folder_id",idStr,updateColumns,tenantYqFolder.getTableName());
                        List<String> daIds = tenantYqdaFolderMapper.selectFileIdByFolderId(idStr, tenantYqdaFolder.getTableName());
                        if(daIds.size()>0){
                            List<String> fzlx = tenantCodeListMapper.selectNodeValByIdAndType(id, "f", tableName);
                            List<String> fgdz = tenantCodeListMapper.selectNodeValByIdAndTypeGd(id, "f", tableName);
                            List<String> fbuling1 = tenantCodeListMapper.selectNodeValByIdAndTypeLen(id, "f", tableName);
                            String fbuling = fbuling1.get(fbuling1.size()-1);
                            String fqueryColumnMax = "max("+fzlx.get(0)+")";
                            queryCondition="id in ("+daIds.stream().collect(Collectors.joining(","))+")";
                            Integer maxfNumber = 0;
                            String maxfno = wenjianzhengliMapper.selectColumnByCondition(fileTableName, fqueryColumnMax, queryCondition);
                            if(StringUtils.isNotEmpty(maxfno)) maxfNumber = Integer.valueOf(maxfno);
                            Iterator<String> iterator2 = daIds.iterator();
                            while (iterator2.hasNext()){
                                maxfNumber+=1;
                                if(maxfNumber.toString().length()>Integer.valueOf(fbuling)){
                                    msg = -4;   //卷内件 件号超出补零位数
                                    break;
                                }
                                String finalfNo = String.format("%0"+fbuling+"d", maxfNumber);
                                String daids = iterator2.next();
                                updateColumns = fDhColumn+"='"+vDH+fgdz.get(0)+finalfNo+"',"+fzlx.get(0)+"='"+maxfNumber+"'";
                                wenjianzhengliMapper.updateColumnById("id",daids,updateColumns,fileTableName);
                                wenjianzhengliMapper.updateColumnById("da_id",daids,updateColumns,tenantYqda.getTableName());
                            }
                        }
                    }else if("0".equals(type)){  //件
                        wenjianzhengliMapper.updateColumnById("da_id",idStr,updateColumns,tenantYqda.getTableName());
                    }
                }
            }
        }
        return msg;
    }

    public Map<String,String> inBatches(String orderStr,String subTableName,List<String> idsArr,String queryColumn,List<String> zlx){
        Map<String,String> fmap = new HashMap<>();
        String orderSql = "";
        if(StringUtils.isNotEmpty(orderStr) && !orderStr.contains(",")){
            orderSql+= "order by";
            String[] split = orderStr.split(",");
            for(String str:split){
                String[] split1 = str.split(" ");
                orderSql += " "+split1[0]+" "+split1[1]+",";
            }
            if(orderSql.endsWith(",")) orderSql = orderSql.substring(0,orderSql.length()-1);
        }
        String ids = idsArr.stream().collect(Collectors.joining(","));
        List<Map<String, Object>> list = wenjianzhengliMapper.selectIdsByOrder(queryColumn+",id", ids, subTableName, orderSql);
        for(int i=0;i<list.size();i++){
            Map<String, Object> map = list.get(i);
            String id = String.valueOf(map.get("ID"));
            String k = "";
            for(int j=0;j<zlx.size()-1;j++){
                String s = zlx.get(j);
                k+=map.get(s)+":";
            }
            if(k.endsWith(":")) k = k.substring(0,k.length()-1);
            if(fmap.containsKey(k)){
                String v = fmap.get(k);
                fmap.put(k,v+","+id);
            }else{
                fmap.put(k,id);
            }
        }
        return fmap;
    }
    public Map<String,String> checkIsExistDh(String categoryId,Integer type,String subTableName,String ids) throws ServiceException{
        Map<String, String> finalIds = new HashMap<>();
        List<Map<String, Object>> maps = wenjianzhengliMapper.selectRqById(ids, subTableName);
        Iterator<Map<String, Object>> iterator = maps.iterator();
        while (iterator.hasNext()){
            Map<String, Object> next = iterator.next();
            String rq = String.valueOf(next.get("RQ"));
            rq = rq.replaceAll("-","");
            String id = String.valueOf(next.get("ID"));
            finalIds.put(id,rq);
        }
        checkRqRight(categoryId,finalIds,type,subTableName,"archiveForm");
        return finalIds;
    }

    public int checkRqRight(String categoryId,Map<String,String> finalIds,Integer type,String subTableName,String source) throws ServiceException {
        int msg = 1;
        String vfeType = type==1?"v":type==0?"f":"";
        HashMap<String, String> map = new HashMap<>();
        Set<Map.Entry<String, String>> entries = finalIds.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        TenantCodeList tenantCodeList = new TenantCodeList();
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        String fileTableName = null;
        if("archiveForm".equals(source)){
            if("v".equalsIgnoreCase(vfeType)){
                TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByTableName(subTableName, new TenantCategory().getTableName());
                fileTableName = tenantCategory.getFileTableName();
            }
        }
        String DHColumn = "";
        String DHfColumn = "";
        //排除日期不在档号定义规则内
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            String daid = next.getKey();
            String value = next.getValue();

            if(!StringUtils.isNotEmpty(value) || "null".equals(value)){
                TenantCodeRule codeRule = new TenantCodeRule();
                codeRule.setCategoryModelId(Long.valueOf(categoryId));
                codeRule.setIsMoren(1);
                List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(codeRule);
                if(tenantCodeRules.size()>0){
                    TenantCodeRule codeRule1 = tenantCodeRules.get(0);
                    if(type==1) {
                        DHColumn = codeRule1.getvColumnname();
                        DHfColumn = codeRule1.getfColumnname();
                    }
                    if(type==0) DHColumn = codeRule1.getfColumnname();
                    List<String> strings = tenantCodeListMapper.selectNodeValByIdAndType(codeRule1.getId(), vfeType, tenantCodeList.getTableName());
                    map.put(daid,strings.get(strings.size()-1));
                }else{
                    iterator.remove();
                    throw new ServiceException("档案日期为空且该门类没有默认档号规则");
                }
                continue;
            }
            value = addZero(value);  //不足八位的rq 末尾补零
            Integer rq = Integer.valueOf(value);
            TenantCodeRule tenantCodeRule = new TenantCodeRule();
            Long ruleId = tenantCodeRuleMapper.selectIdByRqAndCateId(Long.valueOf(categoryId), rq, tenantCodeRule.getTableName());
            if(ruleId==null || ruleId==0){
                TenantCodeRule codeRule = new TenantCodeRule();
                codeRule.setCategoryModelId(Long.valueOf(categoryId));
                codeRule.setIsMoren(1);
                List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(codeRule);
                if(tenantCodeRules.size()>0){
                    TenantCodeRule codeRule1 = tenantCodeRules.get(0);
                    if(type==1) {
                        DHfColumn = codeRule1.getfColumnname();
                        DHColumn = codeRule1.getvColumnname();
                    }
                    if(type==0) DHColumn = codeRule1.getfColumnname();
                    List<String> strings = tenantCodeListMapper.selectNodeValByIdAndType(codeRule1.getId(), vfeType, tenantCodeList.getTableName());
                    map.put(daid,strings.get(strings.size()-1));
                }else{
                    iterator.remove();
                    throw new ServiceException("未查询到档案ID"+daid+"对应的档号规则");
                }
                continue;
            }else{
                TenantCodeRule codeRule1 = tenantCodeRuleMapper.selectYqdaCoderuleModelById(ruleId, tenantCodeRule.getTableName());
                if(type==1){
                    DHfColumn = codeRule1.getfColumnname();
                    DHColumn = codeRule1.getvColumnname();
                }
                if(type==0) DHColumn = codeRule1.getfColumnname();
                List<String> strings = tenantCodeListMapper.selectNodeValByIdAndType(ruleId, vfeType, tenantCodeList.getTableName());
                map.put(daid,strings.get(strings.size()-1));
            }
        }
        if(source==null){
            if(finalIds.size()==0) throw new ServiceException("日期不在档号定义规则内");
        }
        //排除案卷号或件号已生成
        Set<Map.Entry<String, String>> entries1 = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator1 = entries1.iterator();
        while (iterator1.hasNext()){
            Map.Entry<String, String> next = iterator1.next();
            String daid = next.getKey();
            String val = next.getValue();
            List<Map<String, Object>> list = wenjianzhengliMapper.selectColumnById(Long.valueOf(daid), subTableName, val+","+DHColumn);
            Map<String, Object> map1 = list.get(0);
            String dh = String.valueOf(map1.get(DHColumn.toUpperCase()));
            String jh = String.valueOf(map1.get(val.toUpperCase()));
            if("archiveForm".equals(source)){   //仅判断档号字段是否有值

                if("v".equalsIgnoreCase(vfeType)){
                    List<String> list1 = tenantYqdaFolderMapper.selectFileIdByFolderId(daid, tenantYqdaFolder.getTableName());
                    int count=0;
                    for(int i=0;i<list1.size();i++){
                        String s = list1.get(i);
                        List<Map<String, Object>> list2 = wenjianzhengliMapper.selectColumnById(Long.valueOf(s), fileTableName, DHfColumn);
                        Map<String, Object> map2 = list2.get(0);
                        String dhf = String.valueOf(map2.get(DHfColumn.toUpperCase()));
                        if(StringUtils.isEmpty(dhf) || "null".equals(dhf)){
                            count++;
                            break;
                            //iterator1.remove();
                            //break;
                        }
                    }
                    if(StringUtils.isNotEmpty(dh) && !"null".equals(dh) && count==0){
                        iterator1.remove();
                    }
                }else{
                    if(StringUtils.isNotEmpty(dh) && !"null".equals(dh)){
                        iterator1.remove();
                    }
                }
            }else{  //判断档号字段和件号是否同时有值
                if((StringUtils.isNotEmpty(jh) && !"null".equalsIgnoreCase(jh)) && StringUtils.isNotEmpty(dh) && !"null".equals(dh)){
                    iterator1.remove();
                }
            }
            if(source==null){
                if(StringUtils.isNotEmpty(jh) && !"null".equalsIgnoreCase(jh) && (!StringUtils.isNotEmpty(dh) || "null".equals(dh))){

                    map.put(daid,val+":"+jh);   //拼上件号 冒号分割

                }else if((!StringUtils.isNotEmpty(jh) || "null".equalsIgnoreCase(jh) ) && StringUtils.isNotEmpty(dh) && !"null".equals(dh)){
                    //判断档号是否符合档号规则
                    String jhOfDh = checkDH(dh, categoryId, type);
                    if("".equals(jhOfDh)){
                        iterator1.remove();    //已经有档号的但是不符合档号规则
                        msg = -3;
                    }else{
                        map.put(daid,val+":"+jhOfDh);   //拼上件号 冒号分割
                    }
                }
            }
        }
        Set<Map.Entry<String, String>> entries2 = finalIds.entrySet();
        Iterator<Map.Entry<String, String>> iterator2 = entries2.iterator();
        while (iterator2.hasNext()){
            Map.Entry<String, String> next = iterator2.next();
            String key = next.getKey();
            String value = next.getValue();
            if(!map.containsKey(key)){
                iterator2.remove();
            }else{
                if(source==null) {
                    String s = map.get(key);
                    String[] split = s.split(":");
                    if(split.length==2){
                        finalIds.put(key,value+":"+split[1]);
                    }
                }
            }
        }
        if(source==null){
            if(finalIds.size()==0 && msg==1) throw new ServiceException("档号已生成");
        }
        return msg;
    }


    /**
     * 查询规则以及明细是否存在
     */
    public void checkRuleAndList(String categoryId){
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        tenantCodeRule.setCategoryModelId(Long.valueOf(categoryId));
        List<TenantCodeRule> tenantCodeRules = tenantCodeRuleMapper.selectYqdaCoderuleModelList(tenantCodeRule);
        if(tenantCodeRules.size()==0) throw new ServiceException("档号规则未定义");
        //查询规则明细是否存在
        int count = 0;
        for(TenantCodeRule te:tenantCodeRules){
            Long id = te.getId();
            TenantCodeList tenantCodeList = new TenantCodeList();
            tenantCodeList.setArchivalcodeRuleId(id);
            List<TenantCodeList> tenantCodeLists = tenantCodeListMapper.selectYqdaCodelistModelList(tenantCodeList);
            count+=tenantCodeLists.size();
        }
        if(count==0) throw new ServiceException("档号规则明细未定义");
    }


    public Integer getFinalType(JSONObject json){
        String categoryId = json.getString("categoryId");
        String nodeType = json.getString("nodeType");
        String sub_table_name = json.getString("sub_table_name");
        String parentNodeType = json.getString("parentNodeType");
        String parentSubTableName = json.getString("parentSubTableName");
        Integer finalType = null;
        if("c".equalsIgnoreCase(nodeType)){
            if("a".equalsIgnoreCase(parentNodeType)) nodeType = "a";
            if("l".equalsIgnoreCase(parentNodeType)) {
                nodeType = "l";
                sub_table_name = parentSubTableName;
            }
        }
        if("a".equalsIgnoreCase(nodeType)){
            TenantCategory tenantCategory = tenantCategoryService.selectTenanCategoryByID(Long.valueOf(categoryId));
            Integer type = tenantCategory.getType();
            finalType = type;
        }
        if("l".equalsIgnoreCase(nodeType)){
            String[] s = sub_table_name.split("_");
            String lType = s[s.length-2];
            if("X".equalsIgnoreCase(lType)) finalType = 3;
            if("V".equalsIgnoreCase(lType)) finalType = 1;
            if("F".equalsIgnoreCase(lType)) finalType = 0;
        }
        return finalType;
    }

    public String getSubTableName(JSONObject json, TenantCategory tenantCategory){
        Integer type = tenantCategory.getType();
        String nodeType = json.getString("nodeType");
        String sub_table_name = json.getString("sub_table_name");
        String parentNodeType = json.getString("parentNodeType");
        String parentSubTableName = json.getString("parentSubTableName");
        String tableName = null;
        if("l".equalsIgnoreCase(nodeType)){
            tableName = sub_table_name;
        } else{
            if("c".equalsIgnoreCase(nodeType)){
                //String parentNodeType = json.getString("parentNodeType");
                if("a".equalsIgnoreCase(parentNodeType)) tableName = getTableName("a", type,tenantCategory);
                if("l".equalsIgnoreCase(parentNodeType)) tableName = parentSubTableName;
            }
            if("a".equalsIgnoreCase(nodeType)){
                tableName = getTableName("a", type,tenantCategory);
            }
        }
        return tableName;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int delete(JSONObject json) {
        String categoryId = json.getString("categoryId");
        String ids = json.getString("ids");
        String type = json.getString("type");


        //String sub_table_name = json.getString("sub_table_name");
        //String parentNodeType = json.getString("parentNodeType");
        //String parentSubTableName = json.getString("parentSubTableName");

        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory tenantCategory1 = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategory.getTableName());
        TenantCategory category = new TenantCategory();
        BeanUtils.copyProperties(tenantCategory1,category);
       /* if("c".equalsIgnoreCase(nodeType)){
            if("a".equalsIgnoreCase(parentNodeType)) nodeType = "a";
            if("l".equalsIgnoreCase(parentNodeType)) {
                nodeType = "l";
                sub_table_name = parentSubTableName;
            }
        }
        if("a".equalsIgnoreCase(nodeType)){
            deleteIfSelectCategory(ids,tenantCategory1);
        }*/
        //if("l".equalsIgnoreCase(nodeType)){
            //String[] s = sub_table_name.split("_");
            //String lType = s[s.length-2];
            //if("X".equalsIgnoreCase(lType)) {
            //    deleteIfSelectCategory(ids,tenantCategory1);
            //}
            //if("V".equalsIgnoreCase(lType)){
                tenantCategory1.setType(Integer.valueOf(type));
                deleteIfSelectCategory(ids,tenantCategory1);
            //}
            //if("F".equalsIgnoreCase(lType)){
            //    tenantCategory1.setType(0);
            //    deleteIfSelectCategory(ids,tenantCategory1);
            //}
        //}
        //关联关系更新
        if(category.getType() == 3){
            if(Integer.valueOf(type) == 3){
                //删除的是项目

            }else if(Integer.valueOf(type) == 1){
                //删除的是卷
                //更新项目层
                List<Long> itemIdStr = tenantItemFolderMapper.getItemIdByFolderId(ids,category.getItemTableName(),new TenantItemFolder().getTableName());
                for(Long itemId:itemIdStr){
                    List<String> folderIds = tenantItemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId),new TenantItemFolder().getTableName());
                    lixianjieshouService.relevanceMap(category,3,itemId,String.join(",",folderIds));
                }
            }else if(Integer.valueOf(type) == 0){
                //删除件
                 List<String> folderIdStr = tenantYqdaFolderMapper.selectFolderIdByFileId(ids,new TenantYqdaFolder().getTableName());
                for(String folderId:folderIdStr){
                    //更新卷层
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(folderId)){
                        List<String> daIds = tenantYqdaFolderMapper.selectFileIdByFolderId(folderId,new TenantYqdaFolder().getTableName());
                        lixianjieshouService.relevanceMap(category,1,Long.valueOf(folderId),String.join(",",daIds));
                        //更新项目层
                        List<Long> itemIdStr = tenantItemFolderMapper.getItemIdByFolderId(folderId,category.getItemTableName(),new TenantItemFolder().getTableName());
                        for(Long itemId:itemIdStr){
                            List<String> folderIds = tenantItemFolderMapper.selectFolderIdByItemId(String.valueOf(itemId),new TenantItemFolder().getTableName());
                            lixianjieshouService.relevanceMap(category,3,itemId,String.join(",",folderIds));
                        }
                    }
                }
            }
        }else if(category.getType() == 2){
            if(Integer.valueOf(type) == 0){
                //删除件
                //更新卷层
                List<String> folderIdStr = tenantYqdaFolderMapper.selectFolderIdByFileId(ids,new TenantYqdaFolder().getTableName());
                for(String folderId:folderIdStr){
                    List<String> daIds = tenantYqdaFolderMapper.selectFileIdByFolderId(folderId,new TenantYqdaFolder().getTableName());
                    lixianjieshouService.relevanceMap(category,1,Long.valueOf(folderId),String.join(",",daIds));
                }
            }
        }

        String remark = json.getString("remark");
        String oaGdThUrl = sysConfigService.selectConfigByKey("OAGdThUrl");
        if("nfOaTongZhi".equals(remark) && StringUtils.isNotEmpty(oaGdThUrl)){//在线收集，删除并退回至OA
            //档案OA标识和退回原因推送至OA
            String tuiHuiShuoMing = json.getString("tuiHuiShuoMing");
            if(StringUtils.isEmpty(tuiHuiShuoMing)){
                //tuiHuiShuoMing = "无";
            }else {
                String oagdbss = json.getString("oagdbss");
                String oaToken = getOaToken();
                if(!"-1".equals(oaToken)){

                    Map<String, String> requestBodyYb = new HashMap<>();
                    requestBodyYb.put("reason", tuiHuiShuoMing);
                    requestBodyYb.put("summaryId", oagdbss);
                    String postJsonYb  = postJson(oaGdThUrl+"?token="+oaToken, requestBodyYb);
                    com.alibaba.fastjson.JSONObject jsonObjectYb = com.alibaba.fastjson.JSONObject.parseObject(postJsonYb);
                    logger.info("农发与OA退回归档数据接口返回值打印：：：：："+jsonObjectYb.toJSONString());
                }
            }
        }

        return 1;
    }



    public String getOaToken() {
        String oaPath = TokenParamUtil.getOAPath();
        String oaUrl = oaPath+"/seeyon/rest/token";
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("userName", TokenParamUtil.getOAUname());
        requestBody.put("password", TokenParamUtil.getOAPwd());
        String postJson = postJson(oaUrl, requestBody);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(postJson);
        String token = jsonObject.getString("id");
        return token;
    }

    public String postJson(String url, Object requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                new HttpEntity<>(requestBody, headers),
                String.class
        );

        return response.getBody();
    }

    @Override
    public Map<String, Object> getExportTitleAndBody(JSONObject json,List<Map<String, String>> getexportfield) {
        Map<String, Object> map = new HashMap<>();
        //String ids = json.getString("ids");  //选中数据的id
        //String state = json.getString("state");  //数据状态
        String categoryId = json.getString("categoryId");
        TenantCategory tenantCategoryTable = new TenantCategory();
        //TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        ArrayList<String> titles = new ArrayList<>();
        Map<String, Map<String,String>> stringObjectHashMap = new HashMap<>();
        StringBuffer selectColumns = new StringBuffer();
        Iterator<Map<String, String>> iterator = getexportfield.iterator();
        while (iterator.hasNext()){
            Map<String, String> next = iterator.next();
            String field_name = next.get("FIELD_NAME");
            String field_caption = next.get("FIELD_CAPTION");
            String export_column_name = next.get("EXPORT_COLUMN_NAME");
            String showType = String.valueOf(next.get("SHOWTYPE"));
            String finalName = "";
            if(StringUtils.isNotEmpty(export_column_name)) {
                titles.add(export_column_name);
                finalName = export_column_name;
            } else {
                titles.add(field_caption);
                finalName = field_caption;
            }
            if("5".equals(showType)){
                List<TenantSysDictData> tenantSysDictData = tenantSysDictTypeService.selectDictDataByType(field_name);
                if(null!=tenantSysDictData){
                    Map<String, String> map2 = new HashMap<>();
                    for(int i=0;i<tenantSysDictData.size();i++){
                        TenantSysDictData tenantSysDictData1 = tenantSysDictData.get(i);
                        String lb = tenantSysDictData1.getDictLabel();
                        String va = tenantSysDictData1.getDictValue();
                        map2.put(va,lb);
                    }
                    stringObjectHashMap.put(finalName,map2);
                }
            }
            selectColumns.append(field_name).append(",");
        }
        String selectColumnStr = selectColumns.deleteCharAt(selectColumns.length()-1).toString();
        List<List<String>> bodyList = new ArrayList<>();
        //List<Map<String, Object>> list = queryListOfWjzl(json, selectColumnStr, tenantCategory);
        json.put("fields",selectColumnStr);
        List<Map<String, Object>> list = getlistbytreenode(json);
        String[] columnArr = selectColumnStr.toUpperCase().split(",");
        Iterator<Map<String, Object>> iterator1 = list.iterator();
        while (iterator1.hasNext()){
            List<String> valsList = new ArrayList<>();
            Map<String, Object> next = iterator1.next();
            for(String s:columnArr){
                valsList.add(String.valueOf(next.get(s)));
            }
            bodyList.add(valsList);
        }
        map.put("title",titles);
        map.put("body",bodyList);
        map.put("dict",stringObjectHashMap);
        return map;
    }

    public void deleteIfSelectCategory(String ids, TenantCategory tenantCategory1){
        Integer type = tenantCategory1.getType();
        String itemTableName = tenantCategory1.getItemTableName();
        String folderTableName = tenantCategory1.getFolderTableName();
        String fileTableName = tenantCategory1.getFileTableName();
        String efileTableName = tenantCategory1.getEfileTableName();

        String vIds = null;
        String fIds = null;
        for(int i=type;i>=0;i--){
            if(i==3){
                TenantYqItem tenantYqItem = new TenantYqItem();
                TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
                wenjianzhengliMapper.delete(ids,"item_id",tenantYqItem.getTableName());
                wenjianzhengliMapper.delete(ids,"id",itemTableName);
                TenantItemFolder tenantItemFolder = new TenantItemFolder();
                List<String> longs = tenantItemFolderMapper.selectFolderIdByItemId(ids,tenantItemFolder.getTableName());
                List<String> list = tenantYqdaFolderMapper.selectFileIdByItemId(ids, tenantYqdaFolder.getTableName());
                if(list.size()!=0){
                    fIds = String.join(",",list);
                }
                if(longs.size()!=0){
                    vIds = String.join(",",longs);
                }else{
                    //if(list.size()!=0){
                    //    fIds = String.join(",",list);
                        i--;
                    //}
                }
            }
            if(i==1){
                TenantYqFolder tenantYqFolder = new TenantYqFolder();
                TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
                if(vIds!=null){
                    wenjianzhengliMapper.delete(vIds,"folder_id",tenantYqFolder.getTableName());
                    wenjianzhengliMapper.delete(vIds,"id",folderTableName);
                    List<String> longs = tenantYqdaFolderMapper.selectFileIdByFolderId(vIds,tenantYqdaFolder.getTableName());
                    if(longs.size()!=0){
                        if(fIds!=null){
                            fIds = fIds+","+String.join(",",longs);
                        }else{
                            fIds = String.join(",",longs);
                        }
                    }
                }else{
                    wenjianzhengliMapper.delete(ids,"folder_id",tenantYqFolder.getTableName());
                    wenjianzhengliMapper.delete(ids,"id",folderTableName);
                    List<String> longs = tenantYqdaFolderMapper.selectFileIdByFolderId(ids,tenantYqdaFolder.getTableName());
                    if(longs.size()!=0){
                        if(fIds!=null){
                            fIds = fIds+","+String.join(",",longs);
                        }else{
                            fIds = String.join(",",longs);
                        }
                    }
                }
            }
            if(i==0){
                TenantYqda tenantYqda = new TenantYqda();
                if(fIds!=null){
                    wenjianzhengliMapper.delete(fIds,"da_id",tenantYqda.getTableName());
                    wenjianzhengliMapper.delete(fIds,"id",fileTableName);
                    //wenjianzhengliMapper.delete(fIds,"con_table_id",efileTableName);  //电子文件层删除
                }else{
                    wenjianzhengliMapper.delete(ids,"da_id",tenantYqda.getTableName());
                    wenjianzhengliMapper.delete(ids,"id",fileTableName);
                    //wenjianzhengliMapper.delete(ids,"con_table_id",efileTableName);   //电子文件层删除
                }
            }
        }
    }

    public String getTableName(String nodeType, Integer type, TenantCategory tenantCategory){
        String tableName = null;
        if("a".equalsIgnoreCase(nodeType)){  //点击门类节点
            if(0==type)
                tableName = tenantCategory.getFileTableName();
            if(1==type)
                tableName = tenantCategory.getFolderTableName();
            if(3==type)
                tableName = tenantCategory.getItemTableName();
        }
        return tableName;

    }

    public String getOrderColumn(String categoryId,String menuId,String nodeType,Integer type,
                                 String sub_table_name,String parentNodeType,String parentSubTableName){
        String columns = " order by ";
        String fieldType = null;
        if("c".equalsIgnoreCase(nodeType)){
            if("a".equalsIgnoreCase(parentNodeType)) nodeType = "a";
            if("l".equalsIgnoreCase(parentNodeType)) {
                nodeType = "l";
                sub_table_name = parentSubTableName;
            }
        }
        if("a".equalsIgnoreCase(nodeType)){
            if(0==type) fieldType = "jianorder";
            if(1==type) fieldType = "juanorder";
            if(3==type) fieldType = "xiangmuorder";
        }
        if("l".equalsIgnoreCase(nodeType)){
            String[] s = sub_table_name.split("_");
            String lType = s[s.length-2];
            if("X".equalsIgnoreCase(lType)) fieldType = "xiangmuorder";
            if("V".equalsIgnoreCase(lType)) fieldType = "juanorder";
            if("F".equalsIgnoreCase(lType)) fieldType = "jianorder";
        }
        TenantApply tenantApply = new TenantApply();
        String getfieldlist = tenantApplyMapper.getfieldlist(Long.valueOf(menuId), Long.valueOf(categoryId), fieldType, tenantApply.getTableName());
        if(StringUtils.isNotEmpty(getfieldlist)){
            String[] orderArr = getfieldlist.split(",");
            for(int i=0;i<orderArr.length;i++){
                String s = orderArr[i];
                String[] $s = s.split("\\$");
                columns+=$s[0]+" "+$s[1]+",";
            }
        }
        if(columns.endsWith(",")) columns = columns.substring(0,columns.length()-1);
        return columns;
    }

    public String getSelectColumn(String categoryId,String menuId,String nodeType,Integer type,
                                  String sub_table_name,String parentNodeType,String parentSubTableName,Long groupId){
        //jianlistfield,juanlistfield,xiangmulistfield,jianaddfield,juanaddfield,xiangmuaddfield,
        // jianupdatefield,juanupdatefield,xiangmuupdatefield,jianexportfield,juanexportfield,xiangmuexportfield,jianquery,juanquery,xiangmuquery,
        // jianorder,juanorder,xiangmuorder其中任意一个
        String columns = null;
        String fieldType = null;
        Integer mdataListType = null;
        if("c".equalsIgnoreCase(nodeType)){
            if("a".equalsIgnoreCase(parentNodeType)) nodeType = "a";
            if("l".equalsIgnoreCase(parentNodeType)) {
                nodeType = "l";
                sub_table_name = parentSubTableName;
            }
        }
        if("a".equalsIgnoreCase(nodeType)){
            if(0==type) fieldType = "jianlistfield";
            if(1==type) fieldType = "juanlistfield";
            if(3==type) fieldType = "xiangmulistfield";
            mdataListType = type;
        }
        if("l".equalsIgnoreCase(nodeType)){
            String[] s = sub_table_name.split("_");
            String lType = s[s.length-2];
            if("X".equalsIgnoreCase(lType)) {
                fieldType = "xiangmulistfield";
                mdataListType = 3;
            }
            if("V".equalsIgnoreCase(lType)){
                fieldType = "juanlistfield";
                mdataListType = 1;
            }
            if("F".equalsIgnoreCase(lType)){
                fieldType = "jianlistfield";
                mdataListType = 0;
            }
        }
        TenantApply tenantApply = new TenantApply();
        String getfieldlist = tenantApplyMapper.getfieldlist(Long.valueOf(menuId), Long.valueOf(categoryId), fieldType, tenantApply.getTableName());
        if(StringUtils.isNotEmpty(getfieldlist)){
            columns =  getfieldlist.replaceAll("'", "");
        }else{
            StringBuffer sb = new StringBuffer();
            TenantMdataList tenantMdataList = new TenantMdataList();
            tenantMdataList.setIsHidden(0);
            tenantMdataList.setType(mdataListType);
            tenantMdataList.setGroupId(groupId);
            List<TenantMdataList> list = tenantMdataListMapper.selectTenantMdataListList(tenantMdataList);
            Iterator<TenantMdataList> iterator = list.iterator();
            while (iterator.hasNext()){
                TenantMdataList next = iterator.next();
                sb.append(next.getFieldName()).append(",");
            }
            columns = sb.deleteCharAt(sb.length()-1).toString();
        }
        return columns;

    }

    //拼接前端查询条件
    public void concatQueryCondition(JSONArray searchCondition,StringBuilder queryCondition){
        //拼接前端查询条件
        if (searchCondition!=null && searchCondition.size()>0 ) {
            String queryType = null;		//查询类型
            String showType = null;		//展示类型
            String fieldName = null;		//展示类型
            String[] queryValue = new String[2];		//查询值
            for (int j = 0; j < searchCondition.size(); j++) {
                JSONObject jsonObject = searchCondition.getJSONObject(j);
                queryType = jsonObject.getString("queryType"); //根据查询项获取对应的查询类型
                showType = jsonObject.getString("showType"); //根据查询项获取对应的展示类型
                fieldName = jsonObject.getString("column");
                if ("4".equals(queryType)) {	//区间查询会有2个值
                    queryValue[0] = jsonObject.getString("value");		//根据查询项获取对应的查询值
                    queryValue[1] = jsonObject.getString("valueTwo");
                }else{
                    queryValue[0] = jsonObject.getString("value");		//根据查询项获取对应的查询值
                }
                //logger.debug("queryColumns["+j+"] = "+queryColumns[j]+"--"+queryValue[0]);
                queryCondition.append(getQueryCriteriaByType(fieldName,showType,queryType,queryValue));
            }
        }
    }

    /**
     * <p>Title: getQueryCriteriaByType</p>
     * <p>Description: 根据传入的类型type 组合查询条件</p>
     * @param column 列名
     * @param showType 查询类型
     * 		0	不参加查询	暂不考虑;
     * 		1	精确查询		= '匹配值';
     * 		2	模糊查询		like '%匹配值%';
     * 		3	左匹配查询	like '匹配值%';
     * 		4	区间查询		'匹配值1'<列<'匹配值2'	?是否包含=;
     * 		5	列表查询		不做处理;
     * 		6	单选对话框	不做处理;
     * 		7	多选对话框	不做处理;
     * 		8	多词检索		分词 以空格为标志;
     * @param values 查询值
     * @return
     */
    public String getQueryCriteriaByType(String column,String showType,String queryType,String[] values){
        String criteria = " ";
        Integer type = Integer.parseInt(queryType);
        if(8!=type||4!=type){
            if("".equals(values[0])||null==values[0]){
                return "";
            }
        }
        for(int i=0;i<values.length;i++){
            if(StringUtils.isNotEmpty(values[i])){
                values[i] = values[i].trim();
            }
        }
        switch (type) {
            case 0: //不参加查询	暂不考虑;
                criteria = " ";
                break;
            case 1: //精确查询	= '匹配值';
                criteria += column + " = '" + values[0].replace("'","&apos;") + "' and";
                break;
            case 2: //模糊查询	like '%匹配值%';
                criteria += column + " like '%" + values[0].replace("'","&apos;") + "%' and";
                break;
            case 3: //左匹配查询	like '匹配值%';
                criteria += column + " like '" + values[0].replace("'","&apos;") + "%' and";
                break;
            case 4: //区间查询	'匹配值1'<=列<='匹配值2'
                if(StringUtils.isNotEmpty(values[0])) {
                    criteria += "'"+ values[0] + "' <= " + column + " and";
                }
                if(StringUtils.isNotEmpty(values[1])) {
                    criteria += " " + column + " <= '" + values[1] + "' and" ;
                }
                break;
            case 5: //列表查询	不做处理;
                criteria = " ";
                break;
            case 6: //单选对话框	不做处理;
                criteria = " ";
                break;
            case 7: //多选对话框	不做处理;
                criteria = " ";
                break;
            case 8: //多词检索	分词 以空格为标志;	多词检索中 如果有查询列里的值存在空格 怎么处理 (查询时使用""将带空格需要整体查询的值标记 , 例如:"A B")
                String[] value = values[0].split(" ");
                criteria += "(";
                for (int i = 0; i < value.length; i++) {
                    if (i==0) {
                        criteria += column + " like '%" + value[i].replace("'","&apos;") + "%'";
                    }else{
                        criteria += " or "+column + " like '%" + value[i].replace("'","&apos;") + "%'";
                    }
                }
                criteria += ") and";
                break;
            default:
                break;
        }
        return criteria;
    }
    @Override
    public List<Map<String, Object>> getlistbytreenode(JSONObject json) {
        Long categoryId = json.getLong("categoryId");//门类id
        Long menuId = json.getLong("menuId");//菜单id
        String subTableName = json.getString("subTableName");//层级节点的表名
        JSONArray propertyName = json.getJSONArray("propertyName");//分类节点的属性
        JSONArray propertyValue = json.getJSONArray("propertyValue");//分类节点的值
        //Long fondsId=json.getLong("fondsId");//全宗id
        Integer state=json.getInteger("state");//状态
        Integer jsType = null;
        if(json.containsKey("jsType") && StringUtils.isNotEmpty(json.getString("jsType"))){
            jsType = json.getInteger("jsType");
        }

        String fields="id,"+json.getString("fields");//需要查询的字段
        JSONArray jsonArray = json.getJSONArray("searchcolumn");//查询条件
        StringBuilder sb=new StringBuilder(" and ");//用于拼接条件
        String orderstr=json.getString("order");//用于排序
        String ids=json.getString("ids");//用于排序
        int type=-1;
        /**处理查询条件*/
        if(null==jsonArray){
            jsonArray=new JSONArray();
        }
        if(jsonArray.size()>0){
            concatQueryCondition(jsonArray,sb);
        }
        /**处理表名*/
        TenantCategory category=new TenantCategory();
        String tablename="";
        if (null!=subTableName&&!"".equals(subTableName)) {//有层级信息
            tablename=subTableName;
            String tablenametype=subTableName.substring(subTableName.length()-3,subTableName.length()-2);
            if("F".equalsIgnoreCase(tablenametype)){//档案层
                type=0;
            }else if("V".equalsIgnoreCase(tablenametype)){//案卷层
                type=1;
            }else if("X".equalsIgnoreCase(tablenametype)){//项目层
                type=3;
            }else if("E".equalsIgnoreCase(tablenametype)){//电子文件层
                type=2;
            }
        }else{
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            if (tenantCategory.getType()==0){//件
                tablename=tenantCategory.getFileTableName();
            }else if(tenantCategory.getType()==1){//卷
                tablename=tenantCategory.getFolderTableName();
            }else if(tenantCategory.getType()==2){//电子文件
                tablename=tenantCategory.getEfileTableName();
            }else if(tenantCategory.getType()==3){//项目
                tablename=tenantCategory.getItemTableName();
            }
            type=tenantCategory.getType();
        }
        /**处理分类值*/
        if(propertyName.size()>0){
            for (int i = 0; i < propertyName.size(); i++) {
                sb.append(" "+propertyName.get(i)+" = "+"'"+propertyValue.get(i)+"' and ");
            }
        }
        String tiaojian=sb.toString();
        if(StringUtils.isNotEmpty(ids)){   //id不为空时拼上id
            if(tiaojian.endsWith("and ") || tiaojian.endsWith("and")) tiaojian+=" id in ("+ids+") ";
            else tiaojian+=" and id in ("+ids+") ";
        }
        /**处理拼接条件时的sql*/
        if (tiaojian.endsWith("and ")){
            tiaojian=tiaojian.substring(0,tiaojian.length()-4);
        }else if(tiaojian.endsWith("and")){
            tiaojian=tiaojian.substring(0,tiaojian.length()-3);
        }
        /**处理排序*/
        if(null!=orderstr&&!"".equals(orderstr)){
            orderstr=" order by "+orderstr;
        }else{
            String applyorderstr=tenantMdataListService.getorder(categoryId, menuId, type);
            if(null!=applyorderstr&&!"".equals(applyorderstr)){
                orderstr=" order by "+applyorderstr;
            }
        }
        PageUtils.startPage();
        /**查询列表并返回*/
        return wenjianzhengliMapper.getlistbytreenode(new DataScopeBase(menuId),fields,tablename,state,jsType,tiaojian,orderstr);
    }

    @Override
    public List<Map<String, String>> getthbytreenode(JSONObject json) {
        Long categoryId = json.getLong("categoryId");
        Long menuId = json.getLong("menuId");
        String subTableName = json.getString("subTableName");
        JSONObject cjson=new JSONObject();
        cjson.put("categoryId",categoryId);
        cjson.put("menuId",menuId);
        if (null!=subTableName&&!"".equals(subTableName)){//有层级信息
            String type=subTableName.substring(subTableName.length()-3,subTableName.length()-2);
            if("F".equalsIgnoreCase(type)){//档案层
                cjson.put("level","jian");
            }else if("V".equalsIgnoreCase(type)){//案卷层
                cjson.put("level","juan");
            }else if("X".equalsIgnoreCase(type)){//项目层
                cjson.put("level","xiangmu");
            }else if("E".equalsIgnoreCase(type)){//电子文件层
                cjson.put("level","efile");
            }
        }else{//只有门类时,获取最高一级
            TenantCategory category=new TenantCategory();
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            if(tenantCategory.getType()==0){
                cjson.put("level","jian");
            }else if(tenantCategory.getType()==1){
                cjson.put("level","juan");
            }else if(tenantCategory.getType()==2){
                cjson.put("level","efile");
            }else if(tenantCategory.getType()==3){
                cjson.put("level","xiangmu");
            }
        }
        List<Map<String, String>> getshowfield = tenantMdataListService.getshowfield(cjson);
        return getshowfield;
    }

    @Override
    public List<Map<String, String>> getqueryfieldbytreenode(JSONObject json) {
        Long categoryId = json.getLong("categoryId");
        Long menuId = json.getLong("menuId");
        String subTableName = json.getString("subTableName");
        int mdatatype=-1;
        if (null!=subTableName&&!"".equals(subTableName)){//有层级信息
            String type=subTableName.substring(subTableName.length()-3,subTableName.length()-2);
            if("F".equalsIgnoreCase(type)){//档案层
                mdatatype=0;
            }else if("V".equalsIgnoreCase(type)){//案卷层
                mdatatype=1;
            }else if("X".equalsIgnoreCase(type)){//项目层
                mdatatype=3;
            }else if("E".equalsIgnoreCase(type)){//电子文件层
                mdatatype=2;
            }

        }else{//只有门类时,获取最高一级
            TenantCategory category=new TenantCategory();
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            mdatatype=tenantCategory.getType();
        }
        List<Map<String, String>> getqueryfield = tenantMdataListService.getqueryfield(categoryId,menuId,mdatatype);
        return getqueryfield;
    }
}
